<template>
  <div class="system-department-container app-container">
    <el-card>
      <div class="system-department-search mb15">
        <el-input v-model="state.listQuery.name" placeholder="请输入组织名称" style="max-width: 180px"></el-input>
        <el-button type="primary" class="ml10" @click="getDepartmentList">查询
        </el-button>
        <el-button type="success" class="ml10" @click="onOpenSaveOrUpdate('save', null)">新增
        </el-button>
      </div>
      <z-table
          :columns="state.columns"
          :data="state.departmentList"
          ref="tableRef"
          :row-key="'id'"
          :showPage="true"
          v-model:page-size="state.listQuery.pageSize"
          v-model:page="state.listQuery.page"
          :total="state.total"
          @pagination-change="getDepartmentList"
      />

    </el-card>
    <EditDepartment :departmentList="state.departmentList"
                    :allDepartmentTreeList="state.allDepartmentTreeList"
                    @getDepartmentList="getDepartmentList"
                    @getList="getList"
                    ref="EditRef"/>
  </div>
</template>

<script setup name="DepartmentList">
import {h, onMounted, reactive, ref} from 'vue';
import {ElButton, ElMessage, ElMessageBox} from 'element-plus';
import {departmentApi} from "/@/api/hrms/department";
import EditDepartment from "/@/views/hrms/department/editDepartment.vue"


const EditRef = ref();
const tableRef = ref();
const state = reactive({
  columns: [
    {
      key: 'name', label: '组织名称', width: '', align: 'left', show: true, render: ({row}) =>
          h(ElButton, {
            link: true,
            type: "primary",
            onClick: () => {
              onOpenSaveOrUpdate('update', row)
            }
          }, () => row.name),
    },
    {key: 'type', label: '组织类型', width: '', align: 'left', show: true},
    {key: 'department_route', label: '组织路径', width: '', align: 'left', show: true},
    {key: 'parent_name', label: '上级组织', width: '', align: 'left', show: true},
    {key: 'remarks', label: '备注', width: '', align: 'left', show: true},
    {
      label: '操作', columnType: 'string', fixed: 'right', align: 'center', width: '140',
      render: ({row}) => h("div", null, [
        h(ElButton, {
          type: "primary",
          onClick: () => {
            onOpenSaveOrUpdate('update', row)
          }
        }, () => '编辑'),
        h(ElButton, {
          type: "danger",
          onClick: () => {
            deleted(row)
          }
        }, () => '删除')
      ])
    },
  ],
  // list
  departmentList: [],
  allDepartmentTreeList: null,
  listQuery: {
    page: 1,
    pageSize: 200,
    name: '',
  },
  total: 0
});

// 递归组装
const departmentAssembly = (parent_department, all_department) => {
  // console.log('父级组织：', parent_department)
  parent_department.forEach((parent) => {
    all_department.forEach((department) => {
      if (department.parent_id === parent.id) {
        parent.children = parent.children ? parent.children : [];
        parent.children.push(department);
      }
    })
    if (parent.children) departmentAssembly(parent.children, all_department);
  })
  state.allDepartmentTreeList = parent_department
  // console.log('所有组织树：', state.allDepartmentTreeList)
  // state.departmentList = parent_department
};

// 获取组织数
const getList = async () => {
  tableRef.value.openLoading()
  let res = await departmentApi().allDepartmentList({})
  // state.allDepartmentTreeList = res.data
  let parent_department = []
  if (res.data.length > 0) {
    res.data.forEach((department) => {
      if (!department.parent_id) {
        parent_department.push(department)
      }
    })
    departmentAssembly(parent_department, res.data)
  }
  tableRef.value.closeLoading()
};

// 获取组织列表
const getDepartmentList = async () => {

  // console.log('我被调用了')
  tableRef.value.openLoading()
  let res = await departmentApi().departmentList(state.listQuery)
  // console.log('组织数据：', res.data)
  state.departmentList = res.data.rows
  state.total = res.data.rowTotal
  // getList()
  tableRef.value.closeLoading()
};
// 打开新增组织弹窗
// const onOpenAdddepartment = () => {
//   adddepartmentRef.value.openDialog();
// };
// 打开编辑组织弹窗
const onOpenSaveOrUpdate = (editType, row) => {
  EditRef.value.openDialog(editType, row);
};
// 删除当前行
const deleted = (row) => {
  ElMessageBox.confirm('是否删除该条数据, 是否继续?', '提示', {
    confirmButtonText: '删除',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    departmentApi().departmentDeleted(row)
        .then(() => {
          ElMessage.success('删除成功');
          getDepartmentList()
        })
  })
      .catch((err) => {
        ElMessage.info('取消操作' + err);
      });
};
onMounted(() => {
  getList()
  getDepartmentList()
})

</script>

